package com.wswy.wzcx.widget

import android.content.Context
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.wswy.wzcx.R
import kotlinx.android.synthetic.main.layout_choose_input.view.*

class ChooseInputLayout : ConstraintLayout {

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attribute: AttributeSet?) : this(context, attribute, 0)

    constructor(context: Context, attribute: AttributeSet?, defStyle: Int) : super(context, attribute, defStyle) {

        val typedArray = context.obtainStyledAttributes(attribute, R.styleable.ChooseInputLayout)

        val editable = typedArray.getBoolean(R.styleable.ChooseInputLayout_editable,false)
        val rightHint = typedArray.getText(R.styleable.ChooseInputLayout_rightHint)
        val showHelp = typedArray.getBoolean(R.styleable.ChooseInputLayout_showHelp,false)
        val rightDrawable = typedArray.getDrawable(R.styleable.ChooseInputLayout_rightDrawable)

        typedArray.recycle()

        View.inflate(context, R.layout.layout_choose_input,this)

        rightDrawable?.run {
            tv_next_choose.setCompoundDrawablesWithIntrinsicBounds(null,null,this,null)
        }

        if (showHelp){
            img_help.visibility = View.VISIBLE
        }

        if (editable){

            tv_next_choose.text = rightHint
            tv_next_choose.setCompoundDrawables(null,null,null,null)

            val textView = tv_choose_value
            val idx = indexOfChild(textView)

            val lp = textView.layoutParams

            removeViewInLayout(textView)

            val et = EditText(context).apply {
                id = textView.id
                setTextSize(TypedValue.COMPLEX_UNIT_PX,textView.textSize)
                setTextColor(textView.paint.color)
                setHintTextColor(textView.currentHintTextColor)
                setSingleLine()
                background = null

            }

            addViewInLayout(et,idx,lp)

            chooseValue = et
        }else{
            chooseValue = tv_choose_value
        }
    }

    var chooseValue:TextView?=null
    private set

    fun setUI(title:CharSequence?,hint:CharSequence?){
        tv_choose_hint.text = title
        chooseValue?.hint = hint
    }

    fun setHelpClick(block:(()->Unit)?){

        img_help?.setOnClickListener {
            block?.invoke()
        }
    }

    fun setSelectedValue(value:CharSequence?){
        chooseValue?.setText(value)
    }

    fun getSelectedValue():CharSequence? = chooseValue?.text

    override fun setOnClickListener(l: OnClickListener?) {
        super.setOnClickListener(l)
        tv_next_choose.setOnClickListener(l)
    }
}